// lib/pages/menu_page.dart (修改后)
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// 1. 导入 CoffeeModel，不再需要导入 Shop 来获取菜单
import 'package:cesi/model/coffee_model.dart';
// 保留 Shop 的导入，因为购物车功能还需要它
import 'package:cesi/model/shop.dart';
import 'package:cesi/model/coffee.dart';
import 'package:cesi/components/coffee_tile.dart';
import 'package:cesi/theme/color.dart';
import 'package:cesi/components/button.dart';
import 'package:cesi/pages/coffee_details.dart';
import 'package:cesi/components/carousel_widget.dart';
import 'package:cesi/pages/search_results_page.dart';

class MenuPage extends StatefulWidget {
  const MenuPage({super.key});
  @override
  State<MenuPage> createState() => _MenuPageState();
}

class _MenuPageState extends State<MenuPage> {
  final TextEditingController _searchController = TextEditingController();
  // 导航到咖啡详情页
  void _navigateToCoffeeDetails(int index, BuildContext context) {
    // 2. 从 CoffeeModel 获取列表
    final coffeeModel = Provider.of<CoffeeModel>(context, listen: false);
    // 安全检查
    if (index < 0 || index >= coffeeModel.coffees.length) {
      // 如果数据还没加载好，或者索引越界，可以显示一个提示
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('无法加载咖啡详情，请稍后再试')));
      return;
    }
    print('导航到咖啡详情: ${coffeeModel.coffees[index].name}');
    Navigator.push(
      context,
      MaterialPageRoute(
        // 3. 使用从 CoffeeModel 获取的 coffee 对象
        builder: (context) =>
            CoffeeDetailsPage(coffee: coffeeModel.coffees[index]),
      ),
    ).then((_) {
      // 返回后可以刷新数据，如果有需要的话
      // coffeeModel.fetchCoffees();
    });
  }

  // 搜索功能
  void _performSearch(String query, BuildContext context) {
    if (query.trim().isEmpty) return;
    // 4. 从 CoffeeModel 获取数据进行搜索
    final coffeeModel = Provider.of<CoffeeModel>(context, listen: false);
    final allCoffees = coffeeModel.coffees;
    // 过滤搜索结果（不区分大小写）
    final searchResults = allCoffees.where((coffee) {
      return coffee.name.toLowerCase().contains(query.toLowerCase());
    }).toList();
    // 如果没有搜索结果，显示提示
    if (searchResults.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('没有找到与 "$query" 相关的咖啡')));
      return;
    }
    // 导航到搜索结果页面
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SearchResultsPage(
          searchQuery: query,
          searchResults: searchResults,
          onCoffeeTap: (coffee) {
            // 点击搜索结果跳转到详情页
            // 5. 在搜索结果页中，也需要从 CoffeeModel 找到原始 index
            final coffeeModel = Provider.of<CoffeeModel>(
              context,
              listen: false,
            );
            final index = coffeeModel.coffees.indexOf(coffee);
            if (index != -1) {
              Navigator.pop(context); // 关闭搜索结果页
              _navigateToCoffeeDetails(index, context);
            }
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 6. 使用 Consumer<CoffeeModel> 来只重建需要响应数据变化的 UI 部分
    // 这比整个页面都 rebuild 性能更好
    return Consumer<CoffeeModel>(
      builder: (context, coffeeModel, child) {
        // 如果正在加载，显示加载指示器
        if (coffeeModel.isLoading) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }
        // 如果加载出错，显示错误信息
        if (coffeeModel.error != null) {
          return Scaffold(
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.error_outline, color: Colors.red, size: 48),
                  const SizedBox(height: 16),
                  Text(
                    '加载失败',
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.red,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 32.0),
                    child: Text(
                      coffeeModel.error!,
                      style: const TextStyle(color: Colors.grey),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () {
                      // 提供一个重试按钮
                      coffeeModel.fetchCoffees();
                    },
                    child: const Text('重试'),
                  ),
                ],
              ),
            ),
          );
        }
        // 数据加载成功，构建正常的 UI
        // 注意：这里的 shop 只用于购物车功能，不再用于获取菜单
        final shop = Provider.of<Shop>(context, listen: false);
        final coffeeList = coffeeModel.coffees; // 从 CoffeeModel 获取咖啡列表
        return Scaffold(
          backgroundColor: AppColors.cream,
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            foregroundColor: AppColors.textDark,
            elevation: 0,
            leading: Icon(Icons.menu, color: AppColors.primaryBrown),
            title: Center(
              child: Text(
                'Enjoy Coffee',
                style: TextStyle(
                  color: AppColors.textDark,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            actions: [
              // 购物车图标，显示购物车中的商品数量
              Badge(
                label: Text(shop.cart.length.toString()),
                child: IconButton(
                  icon: const Icon(Icons.shopping_cart),
                  onPressed: () {
                    Navigator.pushNamed(context, '/cartPage');
                  },
                ),
              ),
            ],
          ),
          body: Column(
            children: [
              // 促销横幅 (保持不变)
              Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [AppColors.primaryBrown, AppColors.caramel],
                  ),
                  borderRadius: BorderRadius.circular(35),
                ),
                margin: const EdgeInsets.symmetric(horizontal: 20),
                padding: const EdgeInsets.all(10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Column(
                      children: [
                        Text(
                          'Get 32% Promo',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 10),
                        MyButton(
                          text: "Redeem",
                          onTap: () {},
                          backgroundColor: Colors.white,
                          textColor: AppColors.primaryBrown,
                        ),
                      ],
                    ),
                    Image.asset('assets/images/coffee_01.png', height: 90),
                  ],
                ),
              ),
              const SizedBox(height: 25),
              // 搜索栏 (保持不变)
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20.0),
                child: TextField(
                  controller: _searchController,
                  decoration: InputDecoration(
                    filled: true,
                    fillColor: Colors.white,
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: AppColors.lightBrown),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: AppColors.primaryBrown),
                      borderRadius: BorderRadius.circular(20),
                    ),
                    hintText: "search here...",
                    hintStyle: TextStyle(color: AppColors.textLight),
                    suffixIcon: IconButton(
                      icon: Icon(Icons.search, color: AppColors.primaryBrown),
                      onPressed: () {
                        _performSearch(_searchController.text, context);
                      },
                    ),
                  ),
                  onSubmitted: (value) {
                    _performSearch(value, context);
                  },
                ),
              ),
              const SizedBox(height: 25),
              // 菜单标题 (保持不变)
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 25.0),
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "Coffee Menu (${coffeeList.length})", // 显示动态数量
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                      color: AppColors.textDark,
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 10),
              // 咖啡列表 (修改数据源)
              Expanded(
                child: coffeeList.isEmpty
                    ? const Center(
                        child: Text(
                          "暂无咖啡菜单",
                          style: TextStyle(
                            fontSize: 18,
                            color: AppColors.textLight,
                          ),
                        ),
                      )
                    : ListView.builder(
                        scrollDirection: Axis.horizontal,
                        itemCount: coffeeList.length,
                        padding: const EdgeInsets.symmetric(horizontal: 10),
                        itemBuilder: (context, index) => Container(
                          width: 200,
                          margin: const EdgeInsets.only(right: 15),
                          child: CoffeeTile(
                            // 使用从 coffeeModel 获取的 coffee
                            coffee: coffeeList[index],
                            onTap: () =>
                                _navigateToCoffeeDetails(index, context),
                          ),
                        ),
                      ),
              ),
              const SizedBox(height: 20),
              // 轮播推荐 (修改数据源)
              CoffeeCarousel(
                // 使用从 coffeeModel 获取的列表
                coffeeList: coffeeList,
                onTap: (coffee) {
                  // 在轮播图中点击，也需要找到 index
                  final index = coffeeList.indexOf(coffee);
                  if (index != -1) {
                    _navigateToCoffeeDetails(index, context);
                  }
                },
              ),
              const SizedBox(height: 20),
            ],
          ),
        );
      },
    );
  }
}
